
package boundless.web;

import boundless.ejb.AdminBean;
import boundless.ejb.RequestBean;
import boundless.entities.Account;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;


@Named(value = "accountController")
@SessionScoped
public class AccountController implements Serializable {
    @Inject
    @LoggedIn
    Account authenticated;
    @EJB
    private RequestBean req;
    @EJB
    private AdminBean adm;
    private Account current;
    private int selectedItemIndex;

    public AccountController() {
    }

    public Account getSelected() {
        if (current == null) {
            current = new Account();
            selectedItemIndex = -1;
        }

        return current;
    }

    private RequestBean getRequest() {
        return req;
    }
    
    private AdminBean getAdmin() {
        return adm;
    }

    private boolean isUserDuplicated(Account p) {
        return (getRequest().getUserByUsername(p.getUsername()) == null) ? false : true;
    }

    public String create() {
        try {
            if (!isUserDuplicated(current)) {
                getAdmin().createAccount(current);                          
                return "./register.xhtml";
            }
            return "./registerError.xhtml";
        } catch (Exception e) {
            
            return "./registerError.xhtml";
        }
    }

    public void setAccount(Account user) {
        this.authenticated = user;
    }

    public Account getAuthenticated() {
        return authenticated;
    }

    public void setAuthenticated(Account p) {
        this.authenticated = p;
    }
}